package com.wulis.config.security;

import static com.wulis.common.constant.GlobalConstant.UTF_8;
import static com.wulis.common.model.enums.HttpStatusEnum.UNAUTHORIZED;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.wulis.common.wrapper.ApiWrapMapper;
import com.wulis.common.wrapper.ApiWrapper;

/**
 * @author WuliBao
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        AccessDeniedException e)
        throws IOException {
        jsonResponse(httpServletResponse, ApiWrapMapper.wrap(UNAUTHORIZED));
    }
    
    /**
     * 返回json 格式数据
     *
     * @param httpServletResponse httpServletResponse
     * @param wrap wrap
     * @throws IOException IOException
     */
    public static void jsonResponse(HttpServletResponse httpServletResponse, ApiWrapper<Object> wrap)
        throws IOException {
        httpServletResponse.setStatus(HttpStatus.OK.value());
        httpServletResponse.setContentType(APPLICATION_JSON_VALUE);
        httpServletResponse.setCharacterEncoding(UTF_8);
        httpServletResponse.getWriter().write(JSON.toJSONString(wrap));
    }
}
